#!/usr/bin/ruby
$:.unshift File.join(File.dirname(__FILE__))
require 'AWS/EC2'
require 'basic_configuration'
require 'aws_context'
require 'pp'

# Wait for a given instance to enter the active state.

if ARGV[0] == '-?' || ARGV.size != 1 then
  puts "usage: wait-for-active-instance instance-name"
  exit 1
end
name=ARGV[0]

Signal.trap("INT") do
  exit 2
end

config = BasicConfiguration.new
ec2 = AwsContext.instance.ec2(*config.keys)
while true
  begin
    instances = ec2.describe_instances([name])
    #pp instances
    instances.each do |i| 
      i[:instances].each do |o| 
        if o[:state] == "running" then exit 0 end
      end
    end
  rescue
    puts "error #{$!} #{name}"
    exit 1
  end
  sleep 5
end

